<template>
  <globle-dialog ref="globleDialogRef" :title="globleDialogConfig.title" @onClickConfirmBtn="onConfirm"
    @onClickCancelBtn="onCancel" @onDialogColsed="onDialogClosed" @onBeforeColse="onBeforeColse">
    <globle-form ref="globleFormRef" :bindData="globleFormConfig.bindData"
      :itemConfig="globleFormConfig.itemConfig"></globle-form>
  </globle-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { APIData, ICoJudgeParams, ICoManageParams, ICoManage, ICourse, ICoManageList } from '../../../../type';
import { formType, IGlobleFormProps } from '../../../../components/form/type';
import { useAPI } from '../../../../request/api';
import { ElMessage, ElMessageBox } from 'element-plus';

const date = new Date();
const Y = date.getFullYear();
const M = date.getMonth() + 1;
const D = date.getDate();
const startTime = ref([new Date(Y,M,D,12,0,0)]);
const endTime = ref([new Date(Y,M,D,18,0,0)]);
let rowData = {} as ICourse;
let selectedIdList = [] as string[]
const openType = ref(''); //add batchAdd update
const api = useAPI();
const globleDialogRef = ref();
const globleFormRef = ref();
const errorNecessaryMsg = '这是必选项';
const globleDialogConfig = { title: '选课时间设置' };
const globleFormConfig: IGlobleFormProps = reactive({
  bindData: {} as ICoManage,
  itemConfig: [
    {
      type: formType.dateTimePicker,
      label: '开始时间',
      prop: 'beginTime',
      placeholder: '请选择选课开始时间',
      defaultTime: startTime.value,
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'change' }],
    },
    {
      type: formType.dateTimePicker,
      label: '结束时间',
      prop: 'endTime',
      placeholder: '请选择选课结束时间',
      defaultTime: endTime.value,
      // valueFormat: IValueFormat.line,
      rules: [{ required: true, message: errorNecessaryMsg, trigger: 'change' }],
    },
  ],
});

const openDialogByEdit = async (row: ICourse) => {
  rowData = row;
  // await judgeIsBegin();
  openType.value = 'update';
  globleDialogRef.value.isShowDialog = true;
  const data: ICoManage = { beginTime: row.beginTime, endTime: row.endTime }
  globleFormConfig.bindData = data;
};

const openDialogByAdd = (row: ICourse) => {
  rowData = row;
  openType.value = 'add';
  globleDialogRef.value.isShowDialog = true;
  globleFormConfig.bindData = {};
};

const openDialogByBatchAdd = (idList: string[]) => {
  selectedIdList = idList;
  openType.value = 'batchAdd';
  globleDialogRef.value.isShowDialog = true;
  globleFormConfig.bindData = {};
};


//点击取消
const onCancel = () => {
  ElMessageBox.confirm('关闭将不保存更改的数据，确定继续吗').then(() => {
    reset();
    ElMessage.success('您取消了操作');
  }).catch(() => { })
};

//监听弹窗开启
const onDialogClosed = () => {
  const formEl = globleFormRef.value.formRef;
  formEl.clearValidate();
};

//卸载操作
const reset = () => {
  globleDialogRef.value.isShowDialog = false;
  const formEl = globleFormRef.value.formRef;
  globleFormConfig.bindData = {};
  openType.value = '';
  formEl.resetFields();
};

//监听弹窗关闭之前
const onBeforeColse = () => {
  ElMessageBox.confirm('关闭将不保存更改的数据，确定继续吗').then(() => {
    reset();
  }).catch(() => {
    // catch error
  })
};


const emit = defineEmits(['onReGetData','onBeginBatch']);

//点击确定
const onConfirm = () => {
  const formEl = globleFormRef.value.formRef;
  formEl.validate((valid: boolean) => {
    if (valid)
      save().then(code => {
        if (code === 200) {
          emit('onReGetData');
          reset();
        }
      });
    else return false;
  });
};

const save = async () => {
  
  // console.log('formData',formData);
  if (globleFormConfig.bindData.endTime < globleFormConfig.bindData.beginTime) {
    ElMessage.error('开始时间不能大于结束时间');
    return;
  }

  if (openType.value == 'add') return await postSave('开始选课成功')
  else if (openType.value == 'batchAdd') return await postSave('一键开始成功')
  else return await postSave('修改成功')
};

const postSave = async (message: string) => {
  if (openType.value == 'batchAdd') {
    const data: ICoManageList = globleFormConfig.bindData;
    data.courseIdList = selectedIdList;
    const res: APIData = await api.coManage.saveBatch(data);
    if (res.code === 200) {
      ElMessage.success(message);
      emit('onBeginBatch');
    }
    else ElMessage.error(res.message);
    return res.code
  } else {
    const data: ICoManageParams = globleFormConfig.bindData;
    data.courseId = rowData.id;
    const res: APIData = await api.coManage.save(data);
    if (res.code === 200) ElMessage.success(message);
    else ElMessage.error(res.message);
    return res.code
  }
}

const judgeIsBegin = async () => {
  const data: ICoJudgeParams = { courseId: rowData.id }
  const res: APIData = await api.coManage.judgeCoIsBegin(data);
  if (res.code === 200) {
    if (!res.data) ElMessage.error('课程已');
  }
  else ElMessage.error(res.message);
}

defineExpose({
  openDialogByEdit,
  openDialogByAdd,
  openDialogByBatchAdd
});
</script>

<style lang="scss" scoped>
.add-tch {
  article {
    font-size: 18px;
    font-weight: bold;
  }

  p {
    display: inline-block;
    font-weight: bold;
    margin-top: 4px;
    margin-right: 16px;
  }

  padding: 8px;
  padding-top: 0;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 16px;
}
</style>
